const fs = require('fs')
const { resolve } = require('path')
const cheerio = require('cheerio')
const marked = require('marked')

const getNav = (html) => {
  const $ = cheerio.load(html)
  const $div = $('<div></div>')
  $('h2').eq(0).addClass('active')
  $('h2, h3').each(function (index, item) {
    let $item = $(item)
    let $a = $("<a></a>")
    let href = '#' + $item.attr('id')
    $item.removeAttr('id')
    $a.attr('href', href)
    $a.html($item.text())
    $item.html($a)
  })

  $('h2, h3').appendTo($div)
  return $div.html()
}

const getBody = (html) => {
  const $ = cheerio.load(html)
  return $('body').html()
}

function readFileAsync(path) {
  return new Promise(function (resolve) {
    fs.readFile(path, {encoding:'utf8', flag:'r'}, function (err, result) {
      if (err) {
        console.log(err)
      } else {
        resolve(result) 
      }
    })
  })
}

exports.getCourses = async (course, id) => {
  let prefix = `./md`
  const filePath = resolve(prefix, `${course}`, `${id}.md`)
  const md = await readFileAsync(filePath)

  let result = marked(md.toString())
  console.log(result)
  let data = {}
  data = {
    pages: [
      "array"
    ],
    nav: getNav(result),
    body: getBody(result)
  }


  return data
}



